package cn.kawa.org.service.impl;

import cn.kawa.basic.exception.BusinessException;
import cn.kawa.basic.service.impl.BaseServiceImpl;
import cn.kawa.basic.util.BaiduAuditUtils;
import cn.kawa.basic.util.Md5Utils;
import cn.kawa.basic.util.StrUtils;
import cn.kawa.org.domain.Employee;
import cn.kawa.org.domain.Shop;
import cn.kawa.org.domain.ShopLog;
import cn.kawa.org.dto.ShopDto;
import cn.kawa.org.mapper.EmployeeMapper;
import cn.kawa.org.mapper.ShopLogMapper;
import cn.kawa.org.mapper.ShopMapper;
import cn.kawa.org.service.IEmployeeService;
import cn.kawa.org.service.IShopService;
import cn.kawa.user.domain.LoginInfo;
import cn.kawa.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopLogMapper shopLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 用于发送店铺入驻失败短信，接收页面人工审核通过审核的请求 存入通过过程信息
     * @param shopLog
     * @throws MessagingException
     */
    @Override
    public void reject(ShopLog shopLog) throws MessagingException{
        //1.通过shop_id 查询数据， 再修改状态
        Shop shop = shopMapper.loadById(shopLog.getShop_id());
        shop.setState(4);//状态4 ： 审核不通过
        shopMapper.update(shop);
        //2.录入审核日志  shopLog 此时值：shop_id,  note
        shopLog.setState(4);
        shopLog.setAudit_id(2L);//审核人id，以后做
        shopLogMapper.save(shopLog);//存入数据库
        //3.发送邮件给商家
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1309968964@qq.com");
        helper.setSubject("驳回邮件~");
        helper.setText("<h1>你的店铺入驻失败，请检查信息</h1><a href='http://localhost:8080/shop/active/"+shopLog.getShop_id()+"'>点击该链接激活</a>",true);

        // 获取收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        String email = employee.getEmail();
        helper.setTo("1309968964@qq.com");
        // 发送
        javaMailSender.send(mimeMessage);
    }

    /**
     * 用于发送店铺入驻失败短信，接收页面人工审核通过审核的请求 存入通过过程信息
     * @param shopLog
     * @throws MessagingException
     */
    @Override
    public void pass(ShopLog shopLog) throws MessagingException  {// Log:  shop_id,  note
        //1.通过shop_id 查询数据， 再修改状态
        Shop shop = shopMapper.loadById(shopLog.getShop_id());
        shop.setState(2);//状态2 ： 审核通过，待激活
        shopMapper.update(shop);
        //2.录入审核日志  shopLog 此时值：shop_id,  note
        shopLog.setState(2);
        shopLog.setAudit_id(1L);//审核人id，以后做
        shopLogMapper.save(shopLog);//存入数据库
        //3.发送邮件给商家
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1309968964@qq.com");
        helper.setSubject("通过邮件");
        helper.setText("<h1>你的店铺入驻成功!!!</h1><a href='http://localhost:8080/shop/active/"+shopLog.getShop_id()+"'>点击该链接激活</a>",true);

        // 获取收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        String email = employee.getEmail();
        helper.setTo("1309968964@qq.com");
        // 发送
        javaMailSender.send(mimeMessage);


    }

    @Override
    public List<ShopDto> getEcharts() {
        return shopMapper.getEcharts();
    }

    @Override
    public void active(Long id) {
        shopMapper.active(id);
    }

    /**
     * 用于用户存入用户填写的信息，存入shop表以及emp表
     * @param shop 注意页面传来的shop对象中包含了emp对象，其bean属性为admin
     */
    @Override
    public void settlement(Shop shop) {

        System.out.println(shop);
        //实现shop的入驻流程
        //1.非空校验
        /**
         * 先获取admin对象，后面和shop一样对其判断非空并存入表格
         */
        Employee admin = shop.getAdmin();

        if(   StringUtils.isEmpty(shop.getName())
            || StringUtils.isEmpty(shop.getAddress())
            || StringUtils.isEmpty(shop.getTel())
            || StringUtils.isEmpty(admin.getUsername())
            || StringUtils.isEmpty(admin.getPhone())
            || StringUtils.isEmpty(admin.getEmail())
            || StringUtils.isEmpty(admin.getPassword())

        ){
            throw new BusinessException("必填参数不能为空");
        }

        //使用百度ai判断名称是否合法
        Boolean nameTest = BaiduAuditUtils.TextCensor(shop.getName());
        if(!nameTest){
            throw new BusinessException("店铺名称不合法，请检查！");
        }

        //2.两次密码不一致校验
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次密码输入不一致");
        }

        //3.店铺是否注册过的校验
        Shop dbShop = shopMapper.getShopByMessage(shop);
        if(dbShop!=null){
            throw new BusinessException("该店铺已经被注册过");
        }

        //把shop和emp都保存到数据库
        /** 思路：
         * 1.保存employee，获取自增主键
         * 2.把自增的主键设置到shop的admin_id
         * 3.保存shop数据，返回自增主键，
         * 4.赋值给employee  shop_id 字段，更新
         */
        //1.保存employee，获取自增主键
        /**
         * 1.此处改造emp的save方法，存入emp时同时存入loginInfo
         * 2.emp保存时，加密加盐
         */
        //employeeMapper.save(admin);
        /*String salt = StrUtils.getComplexRandomString(32);
        admin.setSalt(salt);//设置admin的密码盐值
        String md5pwd = Md5Utils.encrypByMd5(admin.getPassword() + salt);
        admin.setPassword(md5pwd);
        LoginInfo loginInfo =emp2logininfo(admin);
        loginInfoMapper.save(loginInfo);
        admin.setLogininfo_id(loginInfo.getId());

        employeeMapper.save(admin);*/

        employeeService.add(admin);//测试直接使用抽取的方法完成以上代码

        //2.把自增的主键设置到shop的admin_id
        shop.setAdmin_id(admin.getId());
        //3.保存shop数据，返回自增主键，
        shopMapper.save(shop);
        //4.赋值给employee  shop_id 字段，更新employee数据
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);

    }

    /**
     * 方法 Employee 对象转 LoginInfo对象
     * @param admin
     * @return
     */
    /*private LoginInfo emp2logininfo(Employee admin) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(admin,loginInfo);
        loginInfo.setType(0);
        return loginInfo;
    }*/



    //1.loadAll();
    //2.loadById
    //3.save
    //4.remove
    //5.update
    //6.return new PageList<>(count,shops);
    //7.patchDel

}
